<template>
  <!-- 所有组件配置页面 -->
  <div class="component-config">
    <div class="operate-show-area">
      <widget-view :value="props.value" />
    </div>
    <div class="component-config-content">
      <el-scrollbar height="100%">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane
            v-for="item in tabPaneList"
            :key="item.name"
            :label="item.label"
            :name="item.name"
            class="demo-tabs-pane"
          >
            <el-radio-group
              v-model="childActiveName"
              class="child-tab-radio"
              v-if="activeName === 'styles' && !getOptionsListFLag"
              @change="handleRadioTabChange"
            >
              <el-radio-button
                v-for="(el, num) in childrenTabPaneList"
                :key="num"
                :label="el.name"
              >
                {{ el.label }}
              </el-radio-button>
            </el-radio-group>
          </el-tab-pane>
        </el-tabs>

        <el-form
          label-position="left"
          :model="formData[activeName]"
          :rules="componentConfigRules"
        >
          <template v-for="(item, index) in getOptionsList" :key="index">
            <el-form-item
              :label="item.notShowLabel ? '' : item.label"
              :prop="item.required ? item.name : ''"
            >
              <el-input
                v-model.trim="formData[activeName][item.name]"
                v-if="item.type === 'el-input'"
                @blur="handleInputChange"
                clearable
                :readonly="item.readonly"
              />

              <!-- el-select单选是字符串 -->
              <el-select
                v-model="formData[activeName][item.name]"
                placeholder=""
                v-if="item.type === 'el-select' && !item.multiple"
                @change="handleSelectChange"
                clearable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <!-- el-select多选是数组 -->
              <!-- {{ formData[item.name] }} -->
              <el-select
                v-model="formData[activeName][item.name]"
                placeholder=""
                v-if="
                  item.type === 'el-select' && item.multiple && !item.secondType
                "
                @change="(val) => handleSelectChange(val, item.name)"
                :multiple="item.multiple"
                clearable
                :multiple-limit="
                  ~~formData[activeName]?.yNum?.replace(/[^\d]/g, '') || 0
                "
              >
                <el-option
                  v-for="item in item.selectOptions || getCurrentDataSetOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>

              <!-- 自定义模板 -->
              <el-select
                v-model="formData[activeName][item.name]"
                placeholder=""
                v-if="
                  item.type === 'el-select' &&
                  item.multiple &&
                  item.secondType === 'colorCheckMore'
                "
                @change="(val) => handleSelectChange(val, item.name)"
                :multiple="item.multiple"
                clearable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <div
                    style="display: flex"
                    :style="{ background: item.value }"
                  >
                    <div :style="{ background: item.value }">
                      {{ item.value }}
                    </div>
                  </div>
                </el-option>
              </el-select>

              <el-input-number
                v-model.trim="formData[activeName][item.name]"
                :min="0"
                v-if="item.type === 'el-input-number'"
                @change="handleInputNumberChange"
              />

              <!-- 颜色选择 -->
              <el-color-picker
                v-model="formData[activeName][item.name]"
                show-alpha
                :predefine="predefineColors"
                v-if="item.type === 'el-color-picker'"
                @change="handleUpdateComponentValue"
              />

              <!-- 折叠面板 -->
              <el-collapse
                v-if="item.type === 'el-collapse'"
                style="width: 100%"
                :accordion="true"
              >
                <el-collapse-item :title="item.label" :name="item.name">
                  <template
                    v-for="(childEl, childIndex) in item.children"
                    :key="childIndex"
                  >
                    <el-form-item
                      :label="childEl.label"
                      :prop="childEl.required ? childEl.name : ''"
                      class="collapse-form-item"
                    >
                      <!-- <el-color-picker
                    v-model="
                      formData[activeName][`${item.name}StyleConfig`][
                        childEl.name
                      ]
                    "
                    show-alpha
                    :predefine="predefineColors"
                    @change="handleUpdateComponentValue"
                    v-if="
                      childEl.type === 'el-color-picker' &&
                      formData[activeName][`${item.name}StyleConfig`]
                    "
                  /> -->
                      <el-color-picker
                        v-model="formData[activeName][childEl.name]"
                        show-alpha
                        :predefine="predefineColors"
                        @change="handleUpdateComponentValue"
                        v-if="childEl.type === 'el-color-picker'"
                      />
                      <!-- el-select单选是字符串 -->
                      <el-select
                        v-model="formData[activeName][childEl.name]"
                        placeholder=""
                        v-if="childEl.type === 'el-select' && !childEl.multiple"
                        @change="handleSelectChange"
                        clearable
                      >
                        <el-option
                          v-for="el in childEl.selectOptions"
                          :key="el.value"
                          :label="el.label"
                          :value="el.value"
                        />
                      </el-select>
                      <el-input-number
                        v-model.trim="formData[activeName][childEl.name]"
                        :min="0"
                        v-if="childEl.type === 'el-input-number'"
                        @change="handleInputNumberChange"
                      />
                      <el-slider
                        v-model.trim="formData[activeName][childEl.name]"
                        v-if="childEl.type === 'el-slider'"
                        @change="handleInputNumberChange"
                      />
                      <!-- <el-input
                    v-model.trim="formData[item.name]"
                    v-if="item.type === 'el-input'"
                    @blur="handleInputChange"
                    clearable
                    :readonly="item.readonly"
                  /> -->
                    </el-form-item>
                  </template>
                </el-collapse-item>
              </el-collapse>

              <el-upload
                ref="upload"
                class="upload-demo"
                :action="global.httpUrl + '/cus/v1/fileTools/uploadSingleFile'"
                :limit="1"
                :auto-upload="false"
                :on-exceed="handleExceed"
                :on-success="
                  (response, uploadFile) =>
                    handleAvatarSuccess(response, uploadFile, item.name)
                "
                v-if="item.type === 'el-upload'"
              >
                <template #trigger>
                  <el-button type="primary">选择附件</el-button>
                </template>
                <el-button type="success" @click="submitUpload">
                  上传</el-button
                >
              </el-upload>

              <!-- 关联数据集 -->
              <!-- @update-form-data="handleUpdateFormData" -->
              <dataset-component
                v-if="item.type === 'datasetComponentType'"
                :current-value="props.value"
                @update-form-data="handleUpdateFormData"
                :associatedDatasets="formData[activeName]['associatedDatasets']"
              />
              <!-- 联动设置 -->

              <linkage-setting
                v-if="item.type === 'linkageSettingType'"
                @update-form-data="handleUpdateFormData"
                :current-value="props.value"
                :x-data="formData[activeName]['xAxis']"
                :linkageSetting="formData[activeName]['linkageSetting']"
              />

              <!-- 穿透设置 -->
              <penetration-settings
                v-if="item.type === 'penetrationSettingsType'"
                @update-form-data="handleUpdateFormData"
                :checkedXAndY="checkedXAndY"
                :current-value="props.value"
                :penetrationSettings="
                  formData[activeName]['penetrationSettings']
                "
              />
            </el-form-item>
          </template>
        </el-form>
        <!-- <div contenteditable="true">
          {{ formData.styles }}
        </div>
        <hr /> -->
        <!-- <div contenteditable="true">
      {{ props.value }}
    </div> -->
        <!-- <div contenteditable="true">
          {{ getSuccession }}
        </div> -->
      </el-scrollbar>
    </div>

    <!-- {{ checkedXAndY }} -->
  </div>
</template>

<script setup>
import { reactive, computed, ref, watch, toRefs, inject } from "vue";
import WidgetView from "../widget-view.vue";
import DatasetComponent from "./component/dataset-component.vue";
import LinkageSetting from "./component/linkage-setting.vue";
import PenetrationSettings from "./component/penetration-settings.vue";
import { genFileId } from "element-plus";
import allToolS from "../ui-configs/index";
import { componentConfigRules } from "./constants";
import { getDataSetColumnListApi } from "@/views/design-center/api/data-set";
import useDataSet from "@/views/design-center/store/data-set";
import { cloneDeep } from "lodash";
// import uploadFile from '@/components/upload-file/src/main.vue'
import {
  childrenTabPaneList,
  tabPaneList,
  predefineColors,
} from "./component-constants.js";
const useDataSetStore = useDataSet();

const { currentDataSetWords } = toRefs(useDataSetStore);
const global = inject("global");
const props = defineProps({
  value: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update-list"]);

const formData = ref({
  chartType: props.value.type,
  setups: {
    ...props.value.setups,
  },
  styles: {
    ...props.value.styles,
  },

  // penetrationSettings: {
  //   checkList: []
  // }
});

const activeName = ref("setups");
const childActiveName = ref("groupList");

//获取对应的x轴字段和y轴字段
const getCurrentDataSetOptions = ref([]);

//勾选的x轴和y轴
const checkedXAndY = computed(() => {
  return [
    ...formData.value[activeName.value].xAxis,
    ...formData.value[activeName.value].barChartValue,
  ];
});

//获取配置的所有y轴系列(包含主纵坐标和次纵坐标)----动态样式配置项
const getSuccession = computed(() => {
  let sumOptions = [];
  let includesBarArr = [
    "widget-bar",
    "widget-group-bar",
    "widget-stacked-column",
  ];
  let includesLineAr = [
    "widget-line",
    "widget-group-line",
    "widget-area-chart",
  ];
  let includesBarAndLineArr = ["widget-line-bar"];

  //主纵坐标
  if (formData.value?.["setups"]?.barChartValue) {
    let arr = formData.value?.["setups"]?.barChartValue?.map((item) => {
      let successionOptions = [];
      let barOptions = [
        {
          type: "el-input-number",
          label: "柱状图宽度",
          name: `${item.value}_barW`,
          required: false,
          placeholder: "",
          value: 20, //默认宽320
        },
        {
          type: "el-input-number",
          label: "柱状图倒角",
          name: `${item.value}_barBorderRadius`,
          required: false,
          placeholder: "",
          value: 0, //默认宽320
        },
      ];
      let lineOptions = [
        {
          type: "el-select",
          label: "是否平滑曲线显示",
          name: `${item.value}_lineSmooth`,
          placeholder: "",
          value: false,
          selectOptions: [
            {
              label: "是",
              value: true,
            },
            {
              label: "否",
              value: false,
            },
          ],
        },
      ];

      if (includesBarArr.includes(formData.value.chartType)) {
        successionOptions = successionOptions.concat(barOptions);
      } else if (includesLineAr.includes(formData.value.chartType)) {
        successionOptions = successionOptions.concat(lineOptions);
      } else if (includesBarAndLineArr.includes(formData.value.chartType)) {
        //加入柱状图配置
        successionOptions = successionOptions.concat(barOptions);
      }
      return {
        type: "el-collapse",
        notShowLabel: true,
        label: item.label,
        children: [...successionOptions],
      };
    });

    sumOptions = sumOptions.concat(arr);
  }

  if (formData.value?.["setups"]?.y1Axis) {
    let arr1 = formData.value?.["setups"]?.y1Axis?.map((item) => {
      let successionOptions = [];
      // let barOptions = [
      //   {
      //     type: 'el-input-number',
      //     label: '柱状图宽度',
      //     name: `${item.value}_barW`,
      //     required: false,
      //     placeholder: '',
      //     value: 20 //默认宽320
      //   },
      //   {
      //     type: 'el-input-number',
      //     label: '柱状图倒角',
      //     name: `${item.value}_barBorderRadius`,
      //     required: false,
      //     placeholder: '',
      //     value: 0 //默认宽320
      //   }
      // ];
      let lineOptions = [
        {
          type: "el-select",
          label: "是否平滑曲线显示",
          name: `${item.value}_lineSmooth`,
          placeholder: "",
          value: false,
          selectOptions: [
            {
              label: "是",
              value: true,
            },
            {
              label: "否",
              value: false,
            },
          ],
        },
      ];

      // if (includesBarArr.includes(formData.value.chartType)) {
      //   successionOptions = successionOptions.concat(barOptions);
      // } else if (includesLineAr.includes(formData.value.chartType)) {
      //   successionOptions = successionOptions.concat(lineOptions);
      // } else
      if (includesBarAndLineArr.includes(formData.value.chartType)) {
        //加入柱状图配置
        successionOptions = successionOptions.concat(lineOptions);
      }
      return {
        type: "el-collapse",
        notShowLabel: true,
        label: item.label,
        children: [...successionOptions],
      };
    });

    sumOptions = sumOptions.concat(arr1);
  }
  return sumOptions;
});

const handleRadioTabChange = (value) => {
  // if (value === 'successionList') {
  //   getSuccession.value.forEach((item) => {
  //     if (!formData.value['styles'][`${item.name}`]) {
  //       formData.value[activeName.value][`${item.name}StyleConfig`] = {};
  //     }
  //   });
  // }
  console.log(value, "handleRadioTabChange----------", formData.value);
};

/**
 * @description: 监听组件传递过来的值后,更新echart图
 * @return {*}
 */
// watch(
//   () => formData.value[activeName.value].xAxis,
//   (nv) => {
//     console.log("xAxis", nv);
//     if(activeName.value === 'setups'){
//       // let xAxis = nv.map((item) => item.label);
//       // let yAxis = formData.value.setups.y1Axis.map((item) => item.label);
      
//       formData.value.setups.penetrationSettings.checkList = [...nv,...formData.value.setups.y1Axis]
//       console.log('penetrationSettings',formData.value.setups.penetrationSettings.checkList,[...nv])
//     }
//   },
//   { deep: true }
// );
// watch(
//   () => formData.value[activeName.value].y1Axis,
//   (nv) => {
//     console.log("xAxis", nv);
//     if(activeName.value === 'setups'){
//       let {xAxis=[]} = formData.value.setups.xAxis?.map((item) => item.label).join(',');
//       let {yAxis=[]} = nv.map((item) => item.label).join(',');
//       formData.value.setups.penetrationSettings = [...xAxis,...yAxis]
//     }
//   },
//   { deep: true }
// );


/**
 * @description: 监听关联数据集值的变化,变化后获取对应数据集表字段
 * @return {*}
 */
watch(
  () => formData.value["setups"].associatedDatasets?.id,
  (nv) => {
    formData.value["setups"].xAxis = [];
    formData.value["setups"].barChartValue = [];
    getDataSetColumnList(nv);
  },
  { deep: true }
);

//获取数据集下对应的列表字段用于x-y轴
const getDataSetColumnList = async (dataSetId) => {
  try {
    let res = await getDataSetColumnListApi({
      dataSetId: dataSetId,
    });
    currentDataSetWords.value = cloneDeep(res.data);
    getCurrentDataSetOptions.value = cloneDeep(res.data).map((item) => {
      return {
        label: item.columnAnotherName || item.columnName,
        value: item.columnName,
      };
    });
  } catch (error) {}
};

formData.value[activeName.value].associatedDatasets?.id &&
  getDataSetColumnList(formData.value[activeName.value].associatedDatasets?.id);

/**
 * @description: 获取组件的配置项
 * @param {*} computed
 * @return {*}
 */
const getOptionsListFLag = computed(() => {
  let getOptions = allToolS
    ?.map((item) => item.children)
    .flat()
    .filter((item) => item.type === props.value.type);
  let options = getOptions?.[0]?.options;

  let obj = {
    setups: options.setups, //数据配置项
    //样式配置项包含:组合图,坐标轴,系列,图例
    //其中系列是根据动态获取的主纵坐标轴和次纵坐标轴展示的
    styles: options?.styles,
  };
  // console.log('--------', obj, obj[activeName.value]);

  return Array.isArray(obj[activeName.value]);
});

/**
 * @description: 获取组件的配置项
 * @param {*} computed
 * @return {*}
 */
const getOptionsList = computed(() => {
  let getOptions = allToolS
    ?.map((item) => item.children)
    .flat()
    .filter((item) => item.type === props.value.type);
  let options = getOptions?.[0]?.options;

  let obj = {
    setups: options.setups, //数据配置项
    //样式配置项包含:组合图,坐标轴,系列,图例
    //其中系列是根据动态获取的主纵坐标轴和次纵坐标轴展示的
    styles: options?.styles,
  };
  // console.log('--------', obj, obj[activeName.value]);
  if (Array.isArray(obj[activeName.value])) {
    return obj[activeName.value]; //返回数据配置项
  } else {
    if (childActiveName.value === "successionList") {
      //系列的配置项
      //如果样式配置项是对象,
      return [
        getSuccession.value, //根据不同的列,返回不同列的配置项
        obj[activeName.value]?.[childActiveName.value],
      ].flat();
    } else {
      //如果样式配置项是数组,
      return obj[activeName.value]?.[childActiveName.value];
    }
  }
});

const upload = ref(null);

const handleExceed = (files) => {
  upload.value[0].clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value[0].handleStart(file);
};

/**
 * @description: 提交上传
 * @return {*}
 */
const submitUpload = () => {
  // console.log('upload.value', upload.value[0]);
  upload.value[0].submit && upload.value[0].submit();
};

/**
 * @description: 成功上传
 * @param {*} response
 * @param {*} uploadFile
 * @param {*} key
 * @return {*}
 */
const handleAvatarSuccess = (response, uploadFile, key) => {
  console.log("上传成功,", URL.createObjectURL(uploadFile.raw), response);
  formData.value[activeName.value][key] = response.data;
  handleUpdateComponentValue();
  // emit('update-list', props.value.id, formData.value);
};

/**
 * @description: 更新组件的值
 * @return {*}
 */
const handleUpdateComponentValue = () => {
  emit(
    "update-list",
    props.value.id,
    activeName.value,
    formData.value[activeName.value]
  );
  console.log("formData------------", activeName.value, formData.value);
};

/**
 * @description:输入框值改变后更新组件配置项
 * @return {*}
 */
const handleInputChange = () => {
  handleUpdateComponentValue();
};

/**
 * @description:input-number改变后更新组件配置项
 * @return {*}
 */
const handleInputNumberChange = () => {
  handleUpdateComponentValue();
};

/**
 * @description:select值改变后更新组件配置项
 * @return {*}
 */
const handleSelectChange = (val, name) => {
  console.log(val, name, "6666------------------------------", formData.value);
  // if (['xAxis', 'barChartValue'].includes(name)) {
  //   formData.value.penetrationSettings.checkList.push(...val);
  // }
  handleUpdateComponentValue();
};

/**
 * @description:数据集,联动,穿透组件值改变后更新formData
 * @param {*} key
 * @param {*} value
 * @return {*}
 */
const handleUpdateFormData = (key, value) => {
  formData.value[activeName.value][key] = value;
  console.log("更新后的组件配置项", formData.value, key);
  handleUpdateComponentValue();
};
</script>
<style scoped lang="scss">
.component-config {
  height: 100%;
  padding: 0 0.25rem;
  display: flex;
  flex-direction: column;
  .operate-show-area {
    padding: 0.16rem 0;
    display: flex;
    justify-content: center;
    // border: 0.01rem solid #ccc;
    margin-bottom: 0.16rem;
    width: 100%;
    height: 2rem;
    overflow: auto;
  }
  .component-config-content {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .demo-tabs {
      height: 100%;
      .demo-tabs-pane {
        height: 100%;
      }
    }
  }
  :deep(.el-form-item) {
    width: 100%;
    display: flex;
    .el-form-item__label {
      width: 1rem;
    }
    .el-form-item__content {
      flex: 1;
    }
    //关联数据集,联动,穿透
    .dataset-component,
    .el-select,
    .linkage-setting,
    .penetration-settings {
      width: 100%;
    }
  }
  .child-tab-radio {
    height: 100%;
    margin-bottom: 0.3rem;
  }
  .collapse-form-item {
    margin-bottom: 0.16rem;
  }
}
</style>
